using AutoMapper;
using Microsoft.AspNetCore.Mvc;
using PowerManage.API.Auth;
using PowerManage.Entity;
using PowerManage.Entity.Dtos.Permissions;
using PowerManage.Service;

namespace PowerManage.API.Controllers;

/// <summary>
/// 权限
/// </summary>
[Route("api/[controller]")]
[PermissionAuthorize]
public class PermissionsController : BaseController
{
    private readonly IPermissionService _permissionService;
    private readonly IMapper _mapper;

    public PermissionsController(IPermissionService permissionService, IMapper mapper)
    {
        _permissionService = permissionService;
        _mapper = mapper;
    }

    /// <summary>
    /// 获取所有权限
    /// </summary>
    /// <returns></returns>
    [HttpGet("all")]
    public async Task<IActionResult> GetAll()
    {
        //获取所有权限
        var permissionDtos = await _permissionService.GetAll();
        return Ok(permissionDtos);
    }

    /// <summary>
    /// 添加权限
    /// </summary>
    /// <param name="permissionCreateDto"></param>
    /// <returns></returns>
    [HttpPost]
    public async Task<IActionResult> Post([FromBody] PermissionCreateDto permissionCreateDto)
    {
        //添加权限
        var permission = _mapper.Map<ElePermission>(permissionCreateDto);
        permission = await _permissionService.Add(permission);
        if (permission == null)
        {
            return BadRequest(new ResponseResultDto().SetError("添加权限失败"));
        }

        return Created(String.Empty, permission.Id);
    }

    /// <summary>
    /// 修改权限
    /// </summary>
    /// <param name="id"></param>
    /// <param name="permissionUpdateDto"></param>
    /// <returns></returns>
    [HttpPut("{id}")]
    public async Task<IActionResult> Put(long id, [FromBody] PermissionUpdateDto permissionUpdateDto)
    {
        //获取权限
        ElePermission? permission = await _permissionService.GetById(id);
        if (permission == null)
        {
            return BadRequest(new ResponseResultDto().SetNotFound());
        }

        _mapper.Map(permissionUpdateDto, permission);
        //修改权限
        bool success = await _permissionService.Update(permission);
        if (success)
        {
            return NoContent();
        }
        else
        {
            return BadRequest(new ResponseResultDto().SetError("修改权限失败"));
        }
    }

    /// <summary>
    /// 删除权限
    /// </summary>
    /// <param name="id"></param>
    /// <returns></returns>
    [HttpDelete("{id}")]
    public async Task<IActionResult> Delete(long id)
    {
        //删除权限
        bool success = await _permissionService.Delete(id);
        if (success)
        {
            return NoContent();
        }
        else
        {
            return BadRequest(new ResponseResultDto().SetError("删除权限失败"));
        }
    }
}